<?php

class ProductController extends Controller
{
	/**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   /**
	 * action array filter
	 */
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
   /**
    * Display page index
   */
	public function actionIndex()
	{
	   
      $page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $sidx = isset($_GET['sidx']) ?  $_GET['sidx'] : 'book_date_create'; // Lấy trường cần sắp xếp
      $sord = isset($_GET['sord']) ? $_GET['sord'] : 'DESC'; // Lấy giá trị muốn sắp xếp
      $start = $limit*$page - $limit; // Thứ tự bản ghi bắt đầu lấy
      $rowList = array(10,20,30,50,100);  
      //Biến xác định phiên làm việc của user
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;  
      $list = array();
      $model = new Books();
      $model->unsetAttributes();
      
      $criteria = new CDbCriteria;
      $criteria->limit = $limit;
      $criteria->offset = $start;
      $criteria->order = $sidx . ' ' . $sord;
      if(isset($_POST['Product'])){ // Nếu người dùng search
         $model->attributes = $_POST['Product'];
         $params = array();
         
         if(isset($_POST['start_date'])){
            $criteria->addCondition("pro_date_create >= :start_date", "AND");
            $params[':start_date'] = strtotime(str_replace('/','-',$_POST['start_date']));
         }
         if(isset($_POST['end_date'])){
            $criteria->addCondition("pro_date_create <= :end_date", "AND");
            $params[':end_date'] = strtotime(str_replace('/','-',$_POST['end_date'])) + 86400; //Cuối ngày
         }
         if($model->pro_name != ''){
            $criteria->addCondition("pro_name like :pro_name", "AND");
            $params[':pro_name'] = '%'.$model->pro_name.'%';
         }
         if($model->pro_cat_id != 0){
            $criteria->addCondition("pro_cat_id = :pro_cat_id", "AND");
            $params[':pro_cat_id'] = $model->pro_cat_id;
         }
         if($model->pro_active != 2){
            $criteria->addCondition("pro_active = :pro_active", "AND");
            $params[':pro_active'] = $model->pro_active;
         }
         $criteria->params = $params;
      }
      
      $object = $model->with('category','publisher','authors')->findAll($criteria);
      //CVarDumper::dump($object,10,true);die();
      if(count($object) > 0){
         foreach($object as $item){
            $list[$item->attributes['book_id']] = $item->attributes;
            $list[$item->attributes['book_id']]['cat_name'] = !is_null($item->getRelated('category')) ? $item->getRelated('category')->attributes['cat_name'] : "Chưa chọn";
            $list[$item->attributes['book_id']]['pub_name'] = !is_null($item->getRelated('publisher')) ? $item->getRelated('publisher')->attributes['pub_name'] : "Chưa chọn";
            $authors = $item->getRelated('authors');
            $id_authors = array();
            if(count($authors) > 0){
               $temp = array();
               foreach($authors as $item){
                  $temp[] = $item->aut_id;
               }
               $list[$item->attributes['book_id']]['aut_id'] = $temp;
            }
         }
      }
      //CVarDumper::dump($list,10,true);die();
      $total_record = $model->count($criteria); // Đếm tổng số bản ghi
      if( $total_record >0 ) {
      	$total_pages = ceil($total_record/$limit);
      } else {
      	$total_pages = 0;
      }
      
      //Danh sach danh muc
      $list_category = array();
      $category = new Category();
      $all_cate = $category->getAll();
      $tree_cate = $category->getTree($all_cate);
      
      $this->render('index',array('model' => $model,
                                  'session_user' => $session_user,
                                  'list' => $list,
                                  'rowList' => $rowList,
                                  'page' => $page,
                                  'start' => $start,
                                  'limit' => $limit,
                                  'total_record' => $total_record,
                                  'total_pages' => $total_pages,
                                  'tree_cate' => $tree_cate,));
	}
   
   /**
    * 
    * Display page create
   */
   public function actionCreate(){
      $model = new Books();
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['Books'])){
         $model->attributes = $_POST['Books'];
         $model->book_date_create = time();
         $model->book_date_publish = strtotime(str_replace('/','-',$model->book_date_publish));
         $upload = CUploadedFile::getInstance($model,'book_image');
         if(!is_null($upload)){
            $fileName = date('YmdHis',time());         
            switch($upload->type){
               case 'image/jpeg':
                  $fileName .= '.jpg';
                  break;
               case 'image/png':
                  $fileName .='.png';
                  break;
               default:
                  $fileName .='.gif';
                  break;
            }
            $model->book_image = $fileName;   
         }
         
         if($model->validate()){
            if($model->save()){
               $book_id = $model->book_id;
               $array_id_author = explode(',',$_POST['aut_id']);
               if(count($array_id_author) > 0){
                  foreach($array_id_author as $aut_id){
                     $book_author = new BookAuthor();
                     $book_author->book_id = $book_id;
                     $book_author->aut_id = $aut_id;
                     $book_author->save();
                  }
               }
               $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/product/';
               if(!is_null($upload)){
                  $upload->saveAs($path_to_upload.$fileName);
                  //Resize image
                  $simpleImage = new SimpleImage();
                  $simpleImage->load($path_to_upload.$fileName);
                  $simpleImage->resizeToWidth(800);
                  $simpleImage->save($path_to_upload.$fileName);
                  $simpleImage->load($path_to_upload.$fileName);
                  $simpleImage->resizeToWidth(270);
                  $simpleImage->save($path_to_upload.'thumb_'.$fileName);   
               }
               $message = "Thêm mới sản phẩm thành công";   
               }
            }
            
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }
         }
      //Danh sach danh muc
      $list_category = array();
      $category = new Category();
      $all_cate = $category->getAll();
      $tree_cate = $category->getTree($all_cate);
      unset($tree_cate[0]);
      
      //Danh sách nhà xuất bản
      $list_publisher = array();
      $publishers = Publishers::model()->findAll();
      if(count($publishers) > 0){
         foreach($publishers as $value){
            $list_publisher[$value->pub_id] = $value->pub_name;
         }
      }
      $list_author = array();
      $this->pageTitle = 'Thêm mới sản phẩm';
      $this->layout = '//layouts/cms/create';
      $this->render('create',array(
         'model'=>$model,
         'list_author' => $list_author,
         'session_user' => $session_user,
         'tree_cate' => $tree_cate,
         'list_publisher' => $list_publisher,
         'message' => $message));
   }
   
   /**
    * 
    * Display page edit
   */
   public function actionEdit($id){
      $model = Books::model()->findByPk($id);
      $model->book_date_publish = date('d/m/Y',$model->book_date_publish);
      if($model != null){
         $image = $model->book_image;
         $session_user = md5(time());
         Yii::app()->session['session_user'] = $session_user;
         $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
         $message = '';
         if(isset($_POST['Books'])){
            
            //Xóa những tác giả cũ
            $criteria = new CDbCriteria();
            $criteria->addCondition('book_id = '. $id);
            BookAuthor::model()->deleteAll($criteria);
                        
            $model->attributes = $_POST['Books'];         
            $model->book_date_modify = time();
            $model->book_date_publish = strtotime(str_replace('/','-',$model->book_date_publish));
            $model->book_image = $image;
            $upload = CUploadedFile::getInstance($model,'book_image');
            if(!is_null($upload)){
               $fileName = date('YmdHis',time());         
               switch($upload->type){
                  case 'image/jpeg':
                     $fileName .= '.jpg';
                     break;
                  case 'image/png':
                     $fileName .='.png';
                     break;
                  default:
                     $fileName .='.gif';
                     break;
               }
               $model->book_image = $fileName;   
            }
            $model->book_image = $image;
            
            if($model->validate()){
               if($model->save()){
                  $array_id_author = explode(',',$_POST['aut_id']);
                  if(count($array_id_author) > 0){
                     foreach($array_id_author as $aut_id){
                        $book_author = new BookAuthor();
                        $book_author->book_id = $id;
                        $book_author->aut_id = $aut_id;
                        $book_author->save();
                     }
                  }
                  $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/product/';
                  if(!is_null($upload)){
                     $upload->saveAs($path_to_upload.$fileName);
                     //Resize image
                     $simpleImage = new SimpleImage();
                     $simpleImage->load($path_to_upload.$fileName);
                     $simpleImage->resizeToWidth(800);
                     $simpleImage->save($path_to_upload.$fileName);
                     $simpleImage->load($path_to_upload.$fileName);
                     $simpleImage->resizeToWidth(270);
                     $simpleImage->save($path_to_upload.'thumb_'.$fileName);   
                  }
                  $message = "Thêm mới sản phẩm thành công";   
                  }
               }
               
               if($action_user == 'save'){
                  $this->redirect('/index.php/admin/'.$this->id);
               }
            }
         //Danh sach danh muc
         $list_category = array();
         $category = new Category();
         $all_cate = $category->getAll();
         $tree_cate = $category->getTree($all_cate);
         unset($tree_cate[0]);
         
         //Danh sách nhà xuất bản
         $list_publisher = array();
         $publishers = Publishers::model()->findAll();
         if(count($publishers) > 0){
            foreach($publishers as $value){
               $list_publisher[$value->pub_id] = $value->pub_name;
            }
         }
         $list_author = array();
         if(!$model->isNewRecord){
            $authors_id = BookAuthor::model()->findAllByAttributes(array(
               'book_id' => $model->book_id,
            ));
            if(count($authors_id) > 0){
               $list = array();
               foreach($authors_id as $item){
                  $list[] = $item->aut_id;
               }
               
               //CVarDumper::dump($list,10,true);
               $criteria = new CDbCriteria();
               $criteria->distinct = true;
               $criteria->alias = 'author';
               $criteria->join = 'INNER JOIN book_author ON book_author.aut_id = author.aut_id';
               $criteria->addInCondition('author.aut_id', $list);
               $authors = Authors::model()->findAll($criteria);  
               
               //CVarDumper::dump($authors,10,true);die();
               if(count($authors > 0)){
                  foreach($authors as $item){
                     $temp['id'] = $item->aut_id;
                     $temp['name'] = $item->aut_name;
                     $list_author[] = $temp;
                  }
               }
            }
         }
         
         //echo json_encode($list_author);die();         
         $this->pageTitle = 'Cập nhật thông tin sản phẩm';
         $this->layout = '//layouts/cms/create';
         $this->render('create',array(
            'model'=>$model,
            'list_author' => $list_author,
            'session_user' => $session_user,
            'tree_cate' => $tree_cate,
            'list_publisher' => $list_publisher,
            'message' => $message));
      }
      
   }
   
   
      
   
   /**
    * Deactive record
   */
	public function actionDeactive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE books SET book_active = 0 WHERE book_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   
   /**
    * Active record
   */
	public function actionActive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE books SET book_active = 1 WHERE book_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Delete record
   */
	public function actionDelete(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'DELETE FROM books WHERE book_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   public function actionAjaxTokenInputAuthor(){
      $keyword = Yii::app()->request->getParam('q');
      $criteria = new CDbCriteria();
      $criteria->addCondition('aut_name LIKE :aut_name');
      $criteria->params = array(':aut_name' => '%'.$keyword.'%');
      $authors = Authors::model()->findAll($criteria);
      if(count($authors) > 0){
         $token = array();
         foreach($authors as $item){
            $token[] = array('id' => $item->aut_id,'name' => $item->aut_name);
         }
         echo json_encode($token);
      }
   }

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}